package cn.nfwx.tv.controller;

import android.app.Activity;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.OnLifecycleEvent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.nfwx.tv.R;
import cn.nfwx.tv.base.BaseFragment;
import cn.nfwx.tv.callback.ResponseListener;
import cn.nfwx.tv.db.DownProgramModel;
import cn.nfwx.tv.fragment.search.SearchFragment;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.helper.NetworkHelper;
import cn.nfwx.tv.helper.ThreadHelper;
import cn.nfwx.tv.helper.ValueCallback;
import cn.nfwx.tv.manager.AppointmentManager;
import cn.nfwx.tv.manager.SearchManager;
import cn.nfwx.tv.model.Result;
import cn.nfwx.tv.model.TVProgramModel;
import cn.nfwx.tv.model.TvProgram;
import cn.nfwx.tv.util.LogUtil;
import cn.nfwx.tv.util.SharePrefUtil;
import cn.nfwx.tv.util.ToastUtil;
import cn.nfwx.tv.widget.LoadView;
import cn.nfwx.tv.widget.WxLoadmoreView;
import cn.nfwx.tv.widget.WxRefreshView;

/**
 * Created by dell on 2018/2/26.
 */

public class SearchResultViewController implements View.OnClickListener, LifecycleObserver {

    private Activity mActivity;
    private SearchResultController controller;
    private LinearLayout search_content_lin;
    private TextView search_lookback_btn, search_trailer_btn;
    private TwinklingRefreshLayout trl_search_lookback;

    // 栏目数据源,只保存最初源,不做修改
    //private ArrayList<SubscriptionModel> _mColumns_lookback = new ArrayList<>();
    // 相关视频源
    //private ArrayList<ColumnModel> _mVods_lookback = new ArrayList<>();

    private ArrayList<TvProgram> _mProgram_lookback = new ArrayList<>();

    // 预约的节目
    private ArrayList<TVProgramModel> _programs_trailer = new ArrayList<>();

    private ArrayList<TvProgram> _mProgram_trailer = new ArrayList<>();

    //    private String requestVodCommand;
    private String requestProgramCommand;

    private int pageNo = 1;
    private String keyWord;

    private boolean _isShow = false;

    private static final int LOOKBACK = 1;
    private static final int TRAILER = 2;

    private int status = LOOKBACK;
    private boolean _isColumnDatasSet = false;
    private boolean _isVodDatasSet = false;

    private int stats;

    private static final int STATS_IJK = 2;

    public SearchResultViewController(final SearchFragment searchFragment) {
        mActivity = searchFragment.getActivity();
        View view = searchFragment.getView();
        search_content_lin = findView(view, R.id.search_content_lin);
        search_lookback_btn = findView(view, R.id.search_lookback_btn);
        search_trailer_btn = findView(view, R.id.search_trailer_btn);

        trl_search_lookback = findView(view, R.id.trl_search_lookback);
        WxRefreshView sinaRefreshView = new WxRefreshView(searchFragment.getActivity());
        sinaRefreshView.setArrowResource(R.mipmap.mine_down);
        sinaRefreshView.setTextColor(Color.parseColor("#222222"));
        WxLoadmoreView wxLoadmoreView = new WxLoadmoreView(searchFragment.getActivity());
        trl_search_lookback.setHeaderView(sinaRefreshView);
        trl_search_lookback.setBottomView(wxLoadmoreView);
        trl_search_lookback.setOnRefreshListener(refreshListener);

        controller = new SearchResultController(searchFragment.getView());
        controller.onLoadClickListener(new LoadView.OnLoadClickListener() {
            @Override
            public void onreload() {
                refresh();
            }

            @Override
            public void onnext() {

            }
        });

        search_lookback_btn.setOnClickListener(this);
        search_trailer_btn.setOnClickListener(this);

        controller.getAdapter().setOnItemClickListener(searchFragment);

        controller.getAdapter().setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(final BaseQuickAdapter adapter, View view, final int position) {
                if (adapter.getData().get(position) instanceof TvProgram) {
                    TvProgram tvProgram = (TvProgram) adapter.getData().get(position);
                    switch (view.getId()) {
                        case R.id.btn_appiontment_downlaod: // 预约栏目
                            if (AccountHelper.getInstance().isLogin(mActivity)) {
                                if (!TextUtils.isEmpty(tvProgram.getUrl())) { // 下载
                                    if (!NetworkHelper.getInstance().hasConnection(mActivity)) {
                                        ToastUtil.show(mActivity, R.string.nointernet, Toast.LENGTH_LONG);
                                        return;
                                    }
                                    if (NetworkHelper.getInstance().isConnection4g(mActivity)
                                            && !SharePrefUtil.getDownloadChoose(mActivity)) {
                                        ToastUtil.show(mActivity, R.string.download_4g, Toast.LENGTH_LONG);
                                        return;
                                    }
                                    // 回看更新下载ui
                                    DownloadM3u8Controller.getInstance().download(mActivity, tvProgram, searchFragment.<Integer>bindToLifecycle(), new ValueCallback<Integer>() {
                                        @Override
                                        public void onReceiveValue(Integer value) {
                                            if (mActivity != null && !mActivity.isFinishing()) {
                                                if (value == DownProgramModel.STATS_FAIL) {
                                                    ToastUtil.show(mActivity, "下载失败");
                                                } else if (value == DownProgramModel.STATS_DOWNLOADED) {
                                                    ToastUtil.show(mActivity, "已正在下载");
                                                } else {
                                                    adapter.notifyItemChanged(position);
                                                    ToastUtil.show(mActivity, "正在下载");
                                                }
                                            }
                                        }
                                    });
                                } else {
                                    if (!NetworkHelper.getInstance().hasConnection(mActivity)) {
                                        ToastUtil.show(mActivity, R.string.nointernet, Toast.LENGTH_LONG);
                                        return;
                                    }
                                    AppointmentManager.requestAddAppointment(mActivity, tvProgram.getGid(), new ResponseListener<String>() {
                                        @Override
                                        public void onResponse(String requestTag, String response) {
                                            Result result = JSON.parseObject(response, new TypeReference<Result>() {
                                            }.getType());
                                            if (Result.RESULT_SUCCESS.equals(result.getMessage())) {
                                                mActivity.runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        ToastUtil.show(mActivity, "预约成功", Toast.LENGTH_LONG);
                                                    }
                                                });
                                                AccountHelper.getInstance().refreshDaoAppoint(mActivity,searchFragment.<Boolean>bindToLifecycle(), new ValueCallback<Boolean>() {
                                                    @Override
                                                    public void onReceiveValue(Boolean value) {
                                                        mActivity.runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                adapter.notifyItemChanged(position);
                                                            }
                                                        });
                                                    }
                                                });
                                            }
                                        }

                                        @Override
                                        public void onError(String requestTag, Throwable t) {

                                        }

                                        @Override
                                        public void onFinish() {

                                        }
                                    }, tvProgram.getProgram_id());
                                }
                            } else {
                                Toast.makeText(mActivity, R.string.appoint_no_login, Toast.LENGTH_LONG).show();
                            }
                            break;
                    }
                }
            }
        });
    }

    /**
     *  刷新
     */
    RefreshListenerAdapter refreshListener = new RefreshListenerAdapter() {
        @Override
        public void onRefresh(TwinklingRefreshLayout refreshLayout) {
            refresh();
        }

        @Override
        public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
            loadmore();
        }
    };

    /**
     * 显示回看
     */
    public void showLookBackFragment() {
        if (stats == STATS_IJK) {
            if (status != LOOKBACK) {
                status = LOOKBACK;
                controller.clearData();
                bindLookBackDataSet();
            }
            trl_search_lookback.setEnableLoadmore(false);
            trl_search_lookback.setEnableRefresh(false);
        }
    }

    /**
     * 显示预约
     */
    public void showTrailerFragment() {
        if (stats == STATS_IJK) {
            if (status != TRAILER) {
                controller.showLoading();
                status = TRAILER;
                controller.clearData();
                bindTrailerDataSet();
            }
            trl_search_lookback.setEnableLoadmore(false);
            trl_search_lookback.setEnableRefresh(false);
        }
    }


    /**
     * 显示对应的控件
     */
    public void show() {
        search_content_lin.setVisibility(View.VISIBLE);
        _isShow = true;
        search_trailer_btn.setSelected(false);
        search_lookback_btn.setSelected(true);
    }

    /**
     * 隐藏
     */
    public void hidden() {
        search_content_lin.setVisibility(View.GONE);
        _isShow = false;
        search_trailer_btn.setSelected(false);
        search_lookback_btn.setSelected(true);
    }

    /**
     * 是否显示中
     *
     * @return
     */
    public boolean isShow() {
        return _isShow;
    }

    /**
     * 设置搜索的ijk
     *
     * @param keyWord
     */
    public void setDataIjkKeyword(String keyWord) {
        if (TextUtils.isEmpty(keyWord)) {
            clearLookBackData();
            return;
        }

//        requestVodCommand = null;
        //requestIjkAddKeywordCommand = SearchManager.requestIjkSearchResult(mActivity,keyWord,strCallback);
        this.keyWord = keyWord;
        stats = STATS_IJK;

        controller.setKeyword(keyWord);
        controller.showLoading();
        // 更新信息
        refresh();
    }

    private void bindLookBackDataSet() {
        if (_mProgram_lookback.isEmpty()) {
            requestProgramCommand = SearchManager.requestIjkSearchResult(mActivity, keyWord, callback);
        } else {
            _isColumnDatasSet = true;
            List<Object> datas = new ArrayList<>();
            if (!_mProgram_lookback.isEmpty()) {
                datas.add("相关视频");
            }
            datas.addAll(_mProgram_lookback);
            controller.bindijkPrograms(datas);
        }
    }

    private void bindTrailerDataSet() {
        if (stats == STATS_IJK) {
            if (_mProgram_trailer.isEmpty()) {
                controller.setNodata();
            } else {
                controller.bindijkPrograms(_mProgram_trailer);
            }
        }
    }

    /**
     * 清除数据
     */
    public void clearLookBackData() {
        if (stats == STATS_IJK) {
            _mProgram_lookback.clear();
            _mProgram_trailer.clear();
            controller.clearData();
        }
    }

    /**
     * 加载
     */
    public void refresh() {
        if (stats == STATS_IJK) {
            status = LOOKBACK;
            clearLookBackData();
            trl_search_lookback.setEnableLoadmore(false);
            trl_search_lookback.setEnableRefresh(false);
            bindLookBackDataSet();
        }
    }

    public void loadmore() {
        pageNo++;
        if (stats == STATS_IJK) {

        }
    }


    ResponseListener callback = new ResponseListener<JSONObject>() {
        @Override
        public void onResponse(String requestTag, JSONObject response) {
//            if (requestTag.equals(requestVodCommand)) { // 相关视频
//                try {
//                    final List<ColumnModel> columns = gson.fromJson(response.getString("result"), new TypeToken<List<ColumnModel>>() {
//                    }.getType());
//                    List<P2PSMgr.P2PSFileInfo> fileInfos = DownLoadManager.getDownLoadList(mActivity);
//                    for (ColumnModel columnModel : columns) {
//                        columnModel.setStatus(ColumnModel.PROGRAM_STATUS_LOOKBACK);
//                        for (P2PSMgr.P2PSFileInfo fileInfo : fileInfos) {
//                            if (fileInfo.vid.contains(columnModel.getId())) {
//                                columnModel.setVsid(fileInfo.vsid);
//                                if (fileInfo.percent == 100) {
//                                    columnModel.setStatus(ColumnModel.PROGRAM_STATUS_DOWNED);
//                                } else {
//                                    columnModel.setStatus(ColumnModel.PROGRAM_STATUS_DOWNING);
//                                }
//                                break;
//                            }
//                        }
//                    }
//                    if (pageNo == 1) {
//                        _mVods_lookback.clear();
//                        _isVodDatasSet = true;
//                    }
//                    ThreadHelper.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            controller.bindVodData(getVodsData(columns));
//                            setVodDatas(columns);
//                        }
//                    });
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//           } else
            if (requestTag.equals(requestProgramCommand)) {
                Result<List<TvProgram>> result = JSON.parseObject(response.toString(), new TypeReference<Result<List<TvProgram>>>() {
                }.getType());
                _mProgram_lookback.clear();
                _mProgram_trailer.clear();
                if (Result.RESULT_SUCCESS.equals(result.getMessage())) {
                    List<TvProgram> tvPrograms = result.getData();
                    if (!tvPrograms.isEmpty()) {
                        for (TvProgram tvProgram : tvPrograms) {
                            if (tvProgram.getType() == 0 && !TextUtils.isEmpty(tvProgram.getUrl())) {
                                _mProgram_lookback.add(tvProgram);
                            } else if (tvProgram.getType() == 2) {
                                _mProgram_trailer.add(tvProgram);
                            }
                        }
                    }
                }
                ThreadHelper.post(new Runnable() {
                    @Override
                    public void run() {
                        if (_mProgram_lookback.isEmpty()) {
                            controller.setNodata();
                        } else {
                            List<Object> datas = new ArrayList<>();
                            if (!_mProgram_lookback.isEmpty()) {
                                datas.add("相关视频");
                            }
                            datas.addAll(_mProgram_lookback);
                            controller.bindijkPrograms(datas);
                        }
                    }
                });
            }
        }

        @Override
        public void onError(final String requestTag, Throwable t) {
            ThreadHelper.post(new Runnable() {
                @Override
                public void run() {
//                    if (requestTag.equals(requestVodCommand)) { // 相关视频
//                        controller.showError();
//                        _isVodDatasSet = true;
//                        //setVodDatasSet();
//                    } else
                    if (requestTag.equals(requestProgramCommand)) {
                        controller.showError();
                    }
                }
            });
        }

        @Override
        public void onFinish() {
            ThreadHelper.post(new Runnable() {
                @Override
                public void run() {
                    if (pageNo == 1) {
                        if (trl_search_lookback != null) {
                            trl_search_lookback.finishRefreshing();
                        }
                        if (_isVodDatasSet && _isColumnDatasSet) {
                        }
                    } else {
                        if (trl_search_lookback != null) {
                            trl_search_lookback.finishLoadmore();
                        }
                    }
                }
            });
        }
    };

    /**
     * 设置预约节目总数据
     *
     * @param programDatas
     */
    public void setProgramDatas(List<TVProgramModel> programDatas) {
        _programs_trailer.addAll(programDatas);
    }

    /**
     * 查找控件
     *
     * @param rid
     * @param <T>
     * @return
     */
    public <T extends View> T findView(int rid) {
        return (T) mActivity.findViewById(rid);
    }

    public <T extends View> T findView(View view, int rid) {
        return (T) view.findViewById(rid);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_trailer_btn:
                search_trailer_btn.setSelected(true);
                search_lookback_btn.setSelected(false);
                showTrailerFragment();
                break;
            case R.id.search_lookback_btn:
                search_trailer_btn.setSelected(false);
                search_lookback_btn.setSelected(true);
                showLookBackFragment();
                break;
        }
    }

    /**
     * 获取多余加载的数据
     *
     * @return
     */
    public List<Object> getMoreList() {
        List<Object> objects = new ArrayList<>();
        try {
//            if (_mColumns_lookback.size() > 2) {
//                List<SubscriptionModel> subscriptionModels = _mColumns_lookback.subList(3, _mColumns_lookback.size() - 1);
//                objects.addAll(subscriptionModels);
//            }
        } catch (Exception e) {
            LogUtil.e("nfwx", e.getMessage());
        }
        return objects;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void release() {
        mActivity = null;
        controller.release();
    }
}
